package com.itheima.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.itheima.reggie.common.CustomException;
import com.itheima.reggie.dto.SetmealDto;
import com.itheima.reggie.entity.Setmeal;
import com.itheima.reggie.entity.SetmealDish;
import com.itheima.reggie.mapper.SetmealMapper;
import com.itheima.reggie.service.SetmealDishService;
import com.itheima.reggie.service.SetmealService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;
import java.util.stream.Collectors;

@Service
@Transactional
public class SetmealServiceImpl extends ServiceImpl<SetmealMapper, Setmeal> implements SetmealService {
    /**
     * 保存套餐基本信息和套餐和菜品关联信息
     * @param setmealDto
     */
    @Autowired
    private SetmealDishService setmealDishService;
    @Override
    public void insert(SetmealDto setmealDto) {
//        保存套餐基本信息
        this.save(setmealDto);
//        保存菜品关联信息
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        List<SetmealDish> collect = setmealDishes.stream().map((item) -> {
            item.setSetmealId(setmealDto.getId());
            return item;
        }).collect(Collectors.toList());
        setmealDishService.saveBatch(collect);
    }

    /**
     * 套餐删除
     * @param ids
     */
    @Override
    public void deleteBy(List<Long> ids) {
        LambdaQueryWrapper<Setmeal> lqw=new LambdaQueryWrapper<>();
        lqw.in(Setmeal::getId,ids);
        lqw.eq(Setmeal::getStatus,1);
        int count = this.count(lqw);
        if(count>0){
            throw new CustomException("套餐正在售卖不能删除");
        }
        super.removeByIds(ids);

        LambdaQueryWrapper<SetmealDish> lqw1=new LambdaQueryWrapper<>();
        lqw1.in(SetmealDish::getSetmealId,ids);
        setmealDishService.remove(lqw1);
    }
}
